package com.atguigu.gulimall.ware.listener;

import com.atguigu.common.to.OrderTO;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.to.StockLockedTO;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTO to , Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息");
        try {
            wareSkuService.unlockStock(to);
            //无任何异常，签收消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //远程查询失败，拒绝消息后重新发回队列，让别人消费解锁
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @RabbitHandler
    public void handelOrderCloseRelease(OrderTO orderTO, Channel channel, Message message) throws IOException {
        try {
            wareSkuService.unlockStock(orderTO);
            //无任何异常，签收消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //远程查询失败，拒绝消息后重新发回队列，让别人消费解锁
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
}
